package orderlogisticssrvlogic

import (
	"context"
	"math"
	"strings"

	"gozero-microservices/order-service/rpc/internal/model"
	"gozero-microservices/order-service/rpc/internal/svc"
	"gozero-microservices/order-service/rpc/types/order"
	"gozero-microservices/order-service/rpc/utils"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type OrderLogisticsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

/**
 * 创建订单物流逻辑实例
 *
 * @param context.Context ctx ----------------------必传
 * @param *svc.ServiceContext svcCtx ---------------必传
 * @return *OrderLogisticsLogic
 * @author huwl
 * @date 2025/10/29 12:37:42
 */
func NewOrderLogisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderLogisticsLogic {
	return &OrderLogisticsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

/**
 * 新增订单物流
 *
 * @param uint64 Oid -------------------------------必传,订单Id
 * @param string Message ---------------------------必传,消息
 * @param string GoodsCoverUrl ---------------------必传,商品封面
 * @param uint32 State -----------------------------必传,状态
 * @param string Note ------------------------------非必传,状态
 * @return *order.Result, error
 * @author huwl
 * @date 2025/10/14 12:54:03
 */
func (l *OrderLogisticsLogic) AddOrderLogistics(in *order.AddOrderLogisticsRequest) (*order.Result, error) {

	return &order.Result{Code: 200, Msg: "新增订单物流成功"}, nil
}

func (l *OrderLogisticsLogic) DeleteOrderLogistics(in *order.EditStatusRequest) (*order.Result, error) {

	return &order.Result{Code: 200, Msg: "删除订单物流成功"}, nil
}

func (l *OrderLogisticsLogic) EditOrderLogistics(in *order.EditOrderLogisticsRequest) (*order.Result, error) {

	return &order.Result{Code: 200, Msg: "编辑订单物流成功"}, nil
}

func (l *OrderLogisticsLogic) OrderLogisticsDetail(in *order.DetailRequest) (*order.OrderLogisticsDetailResult, error) {

	return &order.OrderLogisticsDetailResult{}, nil
}

/**
 * 订单物流列表
 *
 * @param uint64 Id --------------------------------非必传,订单物流Id
 * @param string Ids -------------------------------非必传,订单物流Id支持多个
 * @param uint64 Oid -------------------------------非必传,订单Id
 * @param string Oids ------------------------------非必传,订单Id支持多个
 * @param string State -----------------------------非必传,状态支持多个：1,-1
 * @param string Status ----------------------------非必传,状态支持多个：1,-1
 * @param string SortType --------------------------非必传,排序方式
 * @param string SortField -------------------------非必传,排序字段
 * @param int32 PageSize ---------------------------非必传,条数
 * @param uint32 Page ------------------------------非必传,页码
 * @return *order.OrderLogisticsListResult, error
 * @author huwl
 * @date 2025/10/14 12:54:03
 */
func (l *OrderLogisticsLogic) OrderLogisticsList(in *order.QueryOrderLogisticsRequest) (*order.OrderLogisticsListResult, error) {
	params := map[string]interface{}{
		"status <> ?": -2,
	}

	page := in.Page
	pageSize := in.PageSize
	sortType := in.SortType
	sortField := in.SortField

	if in.Id > 0 {
		params["id"] = in.Id
	}
	if in.Ids != "" {
		params["id IN (?)"] = utils.IntSplit(strings.TrimRight(in.Ids, ","), ",")
	}
	if in.Oid > 0 {
		params["oid"] = in.Oid
	}
	if in.Oids != "" {
		params["oid IN (?)"] = utils.IntSplit(strings.TrimRight(in.Oids, ","), ",")
	}
	if in.State != "all" {
		params["state in (?)"] = utils.IntSplit(in.State, ",")
	}
	if in.Status != "all" {
		params["status in (?)"] = utils.IntSplit(in.Status, ",")
	}
	if page <= 0 {
		page = 1
	}
	if pageSize == 0 {
		pageSize = 20
	}
	if sortField == "" {
		sortField = "id"
	}
	if sortType == "" {
		sortType = "desc"
	}

	// 获取数量
	total, err := l.svcCtx.OrderLogisticsModel.GetResultsByTotal(l.ctx, params)
	if err != nil {
		return nil, status.Errorf(codes.Aborted, err.Error())
	}

	orderLogistics := []*order.OrderLogistics{}
	orderLogisticsItems := []*order.OrderLogistics{}
	items := []*model.MallOrderLogistics{}
	if total > 0 {
		err := l.svcCtx.OrderLogisticsModel.GetResultsByParams(l.ctx, &items, params, page, int8(pageSize), sortField+" "+sortType)
		if err != nil {
			return nil, status.Errorf(codes.Aborted, err.Error())
		}

		logisticsItems := []*order.OrderLogistics{}
		for _, item := range items {
			// 组装运输中数据
			if item.State == 4 { // 运输中
				logisticsItems = append(logisticsItems, &order.OrderLogistics{
					Id:         item.Id,
					Oid:        item.Oid,
					Message:    item.Message,
					State:      uint32(item.State),
					Note:       item.Note,
					Status:     int32(item.Status),
					CreateTime: item.CreateTime.String(),
					UpdateTime: item.UpdateTime.String(),
				})
			}

			// 组装全部数据
			orderLogistics = append(orderLogistics, &order.OrderLogistics{
				Id:         item.Id,
				Oid:        item.Oid,
				Message:    item.Message,
				State:      uint32(item.State),
				Note:       item.Note,
				Status:     int32(item.Status),
				CreateTime: item.CreateTime.String(),
				UpdateTime: item.UpdateTime.String(),
			})
		}

		if in.Oid > 0 && in.IsAssembleData > 0 {
			for _, item := range items {
				flag := false
				for _, orderLogisticsItem := range orderLogisticsItems {
					// fmt.Println("orderLogisticsItem.State ==== ", orderLogisticsItem.State)
					if orderLogisticsItem.State != 4 {
						flag = true
					} else {
						flag = false
					}
				}

				if flag || item.State != 4 {
					if item.State == 4 {
						orderLogisticsItems = append(orderLogisticsItems, &order.OrderLogistics{
							Id:         item.Id,
							Oid:        item.Oid,
							Message:    item.Message,
							State:      uint32(item.State),
							Note:       item.Note,
							Status:     int32(item.Status),
							CreateTime: item.CreateTime.String(),
							UpdateTime: item.UpdateTime.String(),
							Items:      logisticsItems[1:],
						})
					} else {
						orderLogisticsItems = append(orderLogisticsItems, &order.OrderLogistics{
							Id:         item.Id,
							Oid:        item.Oid,
							Message:    item.Message,
							State:      uint32(item.State),
							Note:       item.Note,
							Status:     int32(item.Status),
							CreateTime: item.CreateTime.String(),
							UpdateTime: item.UpdateTime.String(),
						})
					}
				}
			}
		}
	}

	// 获取订单快递信息
	orderExpress := model.MallOrderExpress{}
	err = l.svcCtx.OrderExpressModel.Row(l.ctx, &orderExpress, map[string]interface{}{
		"oid": in.Oid,
	})
	if err != nil {
		return nil, status.Errorf(codes.Aborted, err.Error())
	}

	pageTotal := math.Ceil(float64(total) / float64(pageSize))
	orderLogisticsListResult := &order.OrderLogisticsListResult{
		Page:      page,
		Total:     int32(total),
		PageSize:  pageSize,
		PageTotal: int32(pageTotal),
		OrderExpress: &order.OrderExpress{
			Id:            orderExpress.Id,
			Oid:           orderExpress.Oid,
			ExpressId:     uint32(orderExpress.ExpressId),
			ExpressName:   orderExpress.ExpressName,
			ExpressSn:     orderExpress.ExpressSn,
			ExpressMobile: orderExpress.ExpressMobile,
		},
	}
	if in.Oid > 0 && in.IsAssembleData > 0 {
		orderLogisticsListResult.OrderLogistics = orderLogisticsItems
	} else {
		orderLogisticsListResult.OrderLogistics = orderLogistics
	}

	return orderLogisticsListResult, nil
}

func (l *OrderLogisticsLogic) OrderLogisticsTotal(in *order.QueryOrderLogisticsRequest) (*order.TotalResult, error) {

	return &order.TotalResult{}, nil
}
